package com.rocker.graduation.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.rocker.graduation.constants.Constants;
import com.rocker.graduation.entity.CartBean;
import com.rocker.graduation.entity.ErrorBean;
import com.rocker.graduation.service.ICartService;
import com.rocker.graduation.service.ICategoryService;

@Controller
@RequestMapping("/cart")
public class CartController {
	@Autowired
	private ICategoryService categoryService;
	
	@Autowired
	private ICartService cartService;
	
	@RequestMapping("/addToCart.action")
	public ModelAndView addToCart(HttpServletRequest request, Integer id, Integer count){
		ModelAndView mav = new ModelAndView();
		Integer userId = (Integer) WebUtils.getSessionAttribute(request, Constants.USER_ID);
		if (null == userId) {
			mav.setViewName("redirect:/user/facade.action");
			return mav;
		}
		List<CartBean> cartBeans = cartService.addToCart(id, count, userId);
		mav.addObject("items", cartBeans);
		mav.setViewName("redirect:/cart/getCart.action");
		return mav;
	}
	
	@RequestMapping("/getCart.action")
	public ModelAndView getCartItems(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		Integer userId = (Integer) WebUtils.getSessionAttribute(request, Constants.USER_ID);
		if (null == userId) {
			mav.setViewName("redirect:/user/facade.action");
			return mav;
		}
		List<CartBean> cartBeans = cartService.getCartItem(userId);
		mav.addObject("items", cartBeans);
		mav.setViewName("/cart");
		return mav;
	}
	
	@RequestMapping("/removeItem.action/{itemId}")
	@ResponseBody
	public ErrorBean removeItem(HttpServletRequest request, @PathVariable("itemId") Integer itemId){
		Integer userId = (Integer) WebUtils.getSessionAttribute(request, Constants.USER_ID);
		boolean isSuccess = cartService.removeItem(itemId, userId);
		ErrorBean errorBean = new ErrorBean();
		if (!isSuccess) {
			errorBean.setSuccess(Constants.FAILED);
		}
		return errorBean;
	}
	
	@RequestMapping("/removeAll.action")
	@ResponseBody
	public ErrorBean removeAll(HttpServletRequest request){
		ErrorBean errorBean = new ErrorBean();
		Integer userId = (Integer) WebUtils.getSessionAttribute(request, Constants.USER_ID);
		boolean isSuccess = cartService.removeAll(userId);
		if (!isSuccess) {
			errorBean.setSuccess(Constants.FAILED);
		}
		return errorBean;
	}
}
